const http = require('http')
const fs = require('fs')
const path = require('path')


http.createServer((req, res) => {
    var urlObj = new URL(req.url, 'http://localhost')
    var pathname = urlObj.pathname
    if (pathname == '/') {
        var filePath = path.join(__dirname, '/index.html')
        var fileContent = fs.readFileSync(filePath)
        res.writeHead(200, { "Content-Type": "text/html" })
        res.write(fileContent)
        res.end()
    }
    else if (pathname == '/upload') {
        req.setEncoding('binary')
        var str = ''
        req.on('data', (chunk) => {
            str += chunk
        })
        req.on('end', () => {
            var arr = str.split('\r\n')
            var imgArr = arr.splice(4, arr.length - 2)
            var imgStr = imgArr.join('\r\n')
            var buf = Buffer.from(imgStr, 'binary')
            var tm = new Date().getTime()
            fs.writeFileSync(path.join(__dirname, "/upload/" + tm + '.png'), buf, { "encoding": "binary" })
            res.end()
        })
    }
    else if (pathname == '/list') {
        var filePath = path.join(__dirname, '/list.html')
        var fileContent = fs.readFileSync(filePath)
        res.writeHead(200, { "Content-Type": "text/html" })
        res.write(fileContent)
        res.end()
    }
    else if (pathname == '/getlist') {
        var imgs = []
        var filePath = path.join(__dirname, '/upload')
        var files = fs.readdirSync(filePath)
        for (var i = 0; i < files.length; i++) {
            imgs.push(files[i])
        }
        var imgList = JSON.stringify(imgs)
        console.log(imgList)
        res.writeHead(200, { "Content-Type": "text/plain;charset=utf8" })
        res.write(imgList)
        res.end()
    }
    else if(pathname.indexOf('upload/')>=0){
        console.log(pathname)
        var imgPath=path.join(__dirname,'/'+pathname)
        console.log(imgPath)
        var imgBuf=fs.readFileSync(imgPath)
        res.writeHead(200, { "Content-Type": "image/png;" })
        res.write(imgBuf)
        res.end()
    }
}).listen(8081)